/**
 * Copyright (C) 2017 - 2020 https://github.com/joewee
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bifrost.web.controller;

import com.bifrost.common.constant.SessionConstant;
import com.bifrost.common.model.ResultModel;
import com.bifrost.service.PayService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * 威富通支付相关api
 *
 * @author joewee
 * @version 1.0.0
 * @Date 2017/11/24 20:25
 */
@RestController
@RequestMapping("/api/order")
public class SwiftPassPayController {
    /**
     * 日志记录到支付日志中
     */
    private static Logger log = LoggerFactory.getLogger(PayService.class);
    @Autowired
    PayService service;
    @PostMapping("/prePay")
    public ResultModel getPayInfo(@RequestParam String out_trade_no, @RequestParam int total_fee, @RequestParam String body, HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {
        try {
            Object object = req.getSession().getAttribute(SessionConstant.OPEN_ID);
            if(object==null|| StringUtils.isEmpty(object.toString())){
                return ResultModel.error("长时间无操作，会话失效请重新登录");
            }
            req.setAttribute(SessionConstant.OPEN_ID,object.toString());
            if(log.isDebugEnabled()){
                log.debug(String.format("调用预支付接口：%s,金额%d分,描述：%s,OpenId:%s",out_trade_no,total_fee,body,req.getAttribute(SessionConstant.OPEN_ID)));
            }
            Map<String, String> result = service.prePay(req, resp);
            return ResultModel.ok().put("payInfo", result);
        } catch (Exception e) {
            log.error("操作失败，原因：", e);
        }
        return ResultModel.error("获取支付信息失败");
    }
    @PostMapping("/notify")
    public String notify(HttpServletRequest req, HttpServletResponse resp)  {
        return  service.notify(req,resp);
    }
}
